﻿//************************************************************************************************************
// CoNatural.Dto.dll
// Author: Roger Torres
//************************************************************************************************************
// You can use, modify, and distribute the source code and executable programs based on the source code.
// This source code is provided "as is" and without warranties as to performance or merchantability. 
// The author and/or distributors of this source code may have made statements about this source code. 
// Any such statements do not constitute warranties and shall not be relied on by the user in deciding 
// whether to use this source code. This source code is provided without any express or implied warranties 
// whatsoever. Because of the diversity of conditions and hardware under which this source code may be used, 
// no warranty of fitness for a particular purpose is offered. The user is advised to test the source code 
// thoroughly before relying on it. The user must assume the entire risk of using the source code.
//************************************************************************************************************

using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace CoNatural.Dto {
	public class DtoObservableCollection<T> : ObservableCollection<T> where T : Dto {
		private Collection<T> deleted = new Collection<T>();

		protected override void InsertItem(int index, T item) {
			base.InsertItem(index, item);
			item.ChangeTracking = ChangeTracking;
			if (ChangeTracking && item.DtoState == DtoState.Unchanged)
				item.DtoState = DtoState.Inserted;
		}

		protected override void RemoveItem(int index) {
			T item = Items[index];
			base.RemoveItem(index);
			if (ChangeTracking && item.DtoState != DtoState.Inserted)
				deleted.Add(item);
		}

		private bool _changeTracking = false;
		public bool ChangeTracking {
			get { return _changeTracking; }
			set {
				_changeTracking = value;
				foreach (var item in this)
					item.ChangeTracking = _changeTracking;
				foreach (var item in deleted)
					item.ChangeTracking = _changeTracking;
			}
		}

		public DtoObservableCollection<T> GetChanges() {
			var changes = new DtoObservableCollection<T>();

			// copy inserted and updated
			foreach (var dto in this)
				if (dto.DtoState != DtoState.Unchanged)
					changes.Add(dto);

			// copy deleted
			foreach (var dto in deleted) {
				dto.DtoState = DtoState.Deleted;
				changes.Add(dto);
			}

			return changes;
		}
	}
}
